package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    IWemediaClient wemediaClient;

    @Autowired
    CacheService cacheService;

    @Override
    public void computeHotArticle() {
        //先清空以前的
        clearHotCache();
        //1 查询最近5天内发布新闻  > -5
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_WEEK,-5);
        List<ApArticle> articleList = apArticleMapper.findArticleListByLast5days(calendar.getTime());
        //2 计算分值
        List<HotArticleVo> articleVoList =new ArrayList<>();
        if(!articleList.isEmpty()){
            for (ApArticle apArticle : articleList) {
                int score = computeArticleScore(apArticle);
                HotArticleVo vo =new HotArticleVo();
                BeanUtils.copyProperties(apArticle,vo);
                vo.setScore(score);
                articleVoList.add(vo);
            }
        }
        //3 按照频道分类文章,排序(复杂)
        ResponseResult responseResult = wemediaClient.getChannels();
        if(responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())
                &&responseResult.getData()!=null){
            String json = JSON.toJSONString(responseResult.getData());
          List<WmChannel> channels= JSON.parseArray(json, WmChannel.class);
          if(!channels.isEmpty()){
              for (WmChannel channel : channels) {
                  //chanel_list
                  //根据频道获取list
                  List<HotArticleVo> channelArticleVos = articleVoList.stream().
                          filter(x -> x.getChannelId().equals(channel.getId())).
                          collect(Collectors.toList());
                  if(!channelArticleVos.isEmpty()){
//                      Collections.sort(channelArticleVos, new Comparator<HotArticleVo>() {
//                          @Override
//                          public int compare(HotArticleVo o1, HotArticleVo o2) {
//                              return o2.getScore()-o1.getScore();
//                          }
//                      });
                      //排序
                      Collections.sort(channelArticleVos,
                              (HotArticleVo o1, HotArticleVo o2) ->o2.getScore()-o1.getScore());
                      System.out.println(channelArticleVos);
                      if(channelArticleVos.size()>30){
                          channelArticleVos = channelArticleVos.stream().limit(30).collect(Collectors.toList());
                      }
                      //4 按照频道放入缓存
                      cacheService.set(ArticleConstants.HOT_ARTICLE_FIRST_PAGE+channel.getId(),JSON.toJSONString(channelArticleVos));
                  }
              }
          }

        }



        //5 定时支持
    }

    //清空缓存
    private void clearHotCache() {
        Set<String> hotArticleKeys = cacheService.scan(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + "*");
        cacheService.delete(hotArticleKeys);
    }


    private int computeArticleScore(ApArticle apArticle) {
//        阅读权重：1
//        点赞权重：3
//        评论权重：5
//        收藏权重：8

        int score =0;
        if(apArticle.getViews()!=null){
            score+=apArticle.getViews();
        }
        if(apArticle.getLikes()!=null){
            score+=apArticle.getLikes()*3;
        }
        if(apArticle.getComment()!=null){
            score+=apArticle.getComment()*5;
        }
        if(apArticle.getCollection()!=null){
            score+=apArticle.getCollection()*8;
        }
        return score;
    }
}
